package com.hfh.net;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @Author hfh
 * @Date 2022 09 13 11 40
 **/
public class SocketDemo {
    @Test
    public void clientTest() throws IOException {
        Socket s = new Socket(InetAddress.getLocalHost(),9999);
        OutputStream os = s.getOutputStream();
        os.write("测试一下".getBytes());
        os.close();
        s.close();
    }

    @Test
    public void serverTest() throws IOException {
        ServerSocket ss = new ServerSocket(9999);
        Socket s = ss.accept();
        InputStream is = s.getInputStream();
        byte[] bytes = new byte[1024];
        int num = is.read(bytes);
        String str = new String(bytes,0,num);
        System.out.println(s.getInetAddress().toString() + ":" + str);
        is.close();
        s.close();
        ss.close();
    }

}
